<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-07-04 13:40:05
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;

use App\Models\Role;
use App\Models\User;
use App\Models\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

use function PHPUnit\Framework\isEmpty;

class UserRepository extends Repositories
    {
    protected $relation_models = ['department', 'role', 'attachments', 'updator'];
    public function __construct(User $model)
        {
        $this->model = $model;
        }

    public function save($user)
        {
        $user = array_filter($user);
        $id   = isset($user['id']) ? $user['id'] : 0;
        unset($user['id']);
        if (isset($user['password']))
            $user['password'] = Hash::make($user['password']);
        if (isset($user['role'])) {
            $role = $user['role'];
            unset($user['role']);
            }
        $user = $this->model->updateOrCreate(['id' => $id], $user);
        $this->saveManyToMany($role, $user->id, UserRole::class, "role_id", "user_id");
        return $user;
        }

    public function saveDataPermission($role, $user_id)
        {
        return $this->saveManyToMany($role, $user_id, UserRole::class, "role_id", "user_id");
        }

    public function delete($ids)
        {
        $this->model->whereIn("id", $ids)->get()->filter(function ($v)
            {
            $v->delete();
            });
        }

    public function role($user_id)
        {
        return $this->getRelatedData("role", [['employee_id', $user_id]]);
        // return $this->repository->whereId($user_id)->with(['role'])->pluck("role.id");
        }
    public function search($request = null)
        {

        if ($request->has("department_id") && $request->input("department_id") != "") {
            $this->whereDepartment_id($request->input("department_id"));
            }
        if ($request->has("name") && $request->input("name") != "") {
            $this->where(function ($query) use ($request)
                {
                $name = $request->input("name");
                $query->where('name', 'like', '%' . $name . '%')
                    ->orWhere('username', 'like', '%' . $name . '%');
                });
            }
        return parent::search($request);
        }
    }